<template>
  <!-- card -->
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <el-button @click="handleDlg(0)">添加</el-button>
    </div>
    <!-- 表格 -->
    <el-table :data="resourceCategoryData" border style="width: 100%">
      <el-table-column type="index" label="编号" width="80" align="center">
      </el-table-column>
      <el-table-column prop="name" label="类别名称" width="180" align="center">
      </el-table-column>
      <el-table-column
        prop="createdTime"
        label="创建时间"
        :formatter="timeFormatter"
        align="center"
      >
      </el-table-column>
      <el-table-column prop="sort" label="排序" width="100" align="center">
      </el-table-column>
      <el-table-column label="操作" width="180" align="center">
        <!-- 删除编辑-按钮 -->
        <template v-slot="scope">
          <el-button size="mini" @click="handleDlg(scope.row.id)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            @click="handleDeleteCategory(scope.row.id)"
            type="danger"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 对话框 -->
    <!--  接收子组件传来的消息,重新加载数据 -->
    <resource-category-create-or-edit
      ref="categoryDlg"
      @changeCategory="loadAllReaourceCategory"
    />
  </el-card>
</template>
<script>
//1、导入接口函数
import {
  getAllResourceCategory,
  deleteCategory,
} from "@/api/resource-category";
import ResourceCategoryCreateOrEdit from "./create-or-edit";
import dayjs from "dayjs";
export default {
  name: "ResourceCategoryIndex",
  data() {
    return {
      resourceCategoryData: [],
    };
  },
  //3、组件创建完成加载数据
  created() {
    this.loadAllReaourceCategory();
  },
  methods: {
    //2、封装组件内的加载资源类别方法
    loadAllReaourceCategory() {
      getAllResourceCategory().then((res) => {
        if (res.data.code === "000000") {
          this.resourceCategoryData = res.data.data;
        } else {
          this.$message.error("加载资源类别信息失败");
        }
        console.log("加载资源类别", res);
      });
    },
    //封装日期时间格式化函数
    timeFormatter(row, column, value, index) {
      return dayjs(value).format("YYYY-MM-DD");
    },
    //控制创建或编辑对话框
    handleDlg(categoryId = 0) {
      this.$refs.categoryDlg.showAndInit(categoryId);
    },
    //删除资源类别的事件处理函数(调用接口)
    handleDeleteCategory(categoryId = 0) {
      this.$confirm("确认要删除这个资源类别吗?", "删除提示")
        .then(() => {
          deleteCategory(categoryId).then((res) => {
            if (res.data.data) {
              this.$message.success("删除资源类别成功!");
              this.loadAllReaourceCategory();
            } else {
              this.$message.error("删除资源类别失败~");
            }
            console.log("资源类别删除", res);
          });
        })
        .catch(() => {
          this.$message.info("取消了删除资源类别动作");
        });
      // deleteCategory;
    },
  },
  //注册组件
  components: {
    ResourceCategoryCreateOrEdit,
  },
};
</script>
<style lang="scss" scoped></style>
